<template>
  <div class="dashboard-container">
    <!-- Quick Menu -->
    <div class="quick-menu-section">
      <div class="quick-menu-title">快捷菜单</div>
      <div class="quick-menu">
        <div class="menu-items">
          <div class="menu-item" @click="showMetalPurchase">
            <div class="menu-icon blue-icon">
              <el-icon>
                <Box />
              </el-icon>
            </div>
            <span class="menu-label">回购入库</span>
          </div>
          <div class="menu-item" @click="showMetalSales">
            <div class="menu-icon blue-icon">
              <el-icon>
                <ShoppingBag />
              </el-icon>
            </div>
            <span class="menu-label">板料销售</span>
          </div>
          <div class="menu-item" @click="showTransactions">
            <div class="menu-icon blue-icon">
              <el-icon>
                <Document />
              </el-icon>
            </div>
            <span class="menu-label">交易记录</span>
          </div>
        </div>
        <el-button type="primary" @click="refreshData" :loading="refreshing" class="refresh-button">刷新</el-button>
      </div>
    </div>

    <!-- Card 1: 回收销售数据 -->
    <el-card class="data-card">
      <template #header>
        <div class="card-header">
          <span>回收销售数据</span>
        </div>
      </template>
      <el-table :data="recoverySalesData" style="width: 100%" v-loading="loadingRecoveryData">
        <el-table-column prop="title" label="统计日期" />
        <el-table-column label="支出">
          <template #default="scope">
            {{ scope.row.paymentAmount?.value ?? 0 }}
          </template>
        </el-table-column>
        <el-table-column label="收入">
          <template #default="scope">
            {{ scope.row.receivedAmount?.value ?? 0 }}
          </template>
        </el-table-column>
        <el-table-column label="毛利/毛利率">
          <template #default="scope">
            {{ formatProfit(scope.row) }}
          </template>
        </el-table-column>
        <!-- Metal commodity columns -->
        <el-table-column v-for="metal in metalCommodities" :key="metal.id" :label="metal.name">
          <el-table-column :prop="'sales_' + metal.id" :label="'销售'" width="100">
            <template #default="scope">
              {{ scope.row[`sales_${metal.id}`] }}
            </template>
          </el-table-column>
          <el-table-column :prop="'purchase_' + metal.id" :label="'回购'" width="100">
            <template #default="scope">
              {{ scope.row[`purchase_${metal.id}`] }}
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- Cards 2 & 3: 存欠料存欠款 and 库存 (placed side by side) -->
    <el-row :gutter="20" style="margin-top: 20px; max-width: 1520px;">
      <!-- Card 2: 存欠料存欠款 -->
      <el-col :span="12">
        <el-card class="data-card equal-height-card">
          <template #header>
            <div class="card-header">
              <span>存欠料存欠款</span>
            </div>
          </template>
          <el-table :data="balanceTableData" style="width: 100%" v-loading="loadingBalanceData">
            <el-table-column prop="title" label="类型" />
            <el-table-column label="存欠料">
              <template #default="scope">
                {{ scope.row.innerBalance ?? 0 }}
              </template>
            </el-table-column>
            <el-table-column label="实时价">
              <template #default="scope">
                {{ scope.row.price }}
              </template>
            </el-table-column>
            <el-table-column label="市值">
              <template #default="scope">
                {{ scope.row.worth }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <!-- Card 3: 总仓 -->
      <el-col :span="12">
        <el-card class="data-card equal-height-card">
          <template #header>
            <div class="card-header">
              <span>库存</span>
            </div>
          </template>
          <el-table :data="fundAccountList" style="width: 100%" v-loading="loadingFundAccounts">
            <el-table-column label="品类" align="center" prop="name"></el-table-column>
            <el-table-column label="库存" align="center" prop="balance"></el-table-column>
            <el-table-column label="实时价" align="center">
              <template #default="scope">
                {{ getMetalPrice(scope.row) }}
              </template>
            </el-table-column>
            <el-table-column label="市值" align="center">
              <template #default="scope">
                {{ getMarketValue(scope.row) }}
              </template>
            </el-table-column>
            <el-table-column v-if="showStoreOption" label="所属门店" align="center">
              <template #default="scope">
                {{ scope.row.store ? scope.row.store.name : '无' }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { MetalUiAction } from '../public/engine/uiAction/metalUiAction.js';
import { CommodityUiAction } from '../public/engine/uiAction/commodityUiAction.js';
import { SubCommodityFilter, SubCommodityMetalFilterTypeEnum } from '../public/engine/commodity/subCommodity.js';
import { DataPage } from '../public/network/communicationConverter.js';
import { delCombineOrderInOutStatic, delCurrentPeriodBalance } from '../public/network/api.js';
import { MetalUtil } from '../public/utils/metalUtil.js';
import { FundUiAction } from '../public/engine/uiAction/fundUiAction'
import { Definition } from '../public/engine/common/definition'
import { FundAccountFilter } from '../public/engine/funds/fundAccount.js'
import { deleteFundAccountListNetworkCacheData } from '../public/network/api.js'
import { FundAccountInsideType } from '../public/engine/common/fundDefinition';
import { Engine } from '../public/engine/engine.js'
import { uiNavigation } from '../public/views/uiEntrance/uiNavigation.js'


export default {
  name: 'DashboardPage',
  data() {
    return {
      metalUiAction: new MetalUiAction(),
      commodityUiAction: new CommodityUiAction(),
      recoverySalesData: [],
      balanceData: null,
      metalCommodities: [],
      loadingRecoveryData: false,
      loadingBalanceData: false,
      refreshing: false,
      metalUtil: MetalUtil.getInstance(),
      realPriceData: null,
      // New fund account data
      fundAccountList: [],
      loadingFundAccounts: false,
      fundUiAction: new FundUiAction(),
      filter: new FundAccountFilter({ accountInsideType: FundAccountInsideType.MerchantMetalAccount })
    };
  },
  computed: {
    balanceTableData() {
      // Process balance data to include metal-specific rows
      if (!this.balanceData || !this.metalCommodities.length) {
        return [];
      }

      console.log('create balanceTableData');

      const result = [];

      let totalWorth = 0;

      // Add overall balance row
      result.push({
        title: '存欠款',
        innerBalance: '',
        price: '',
        worth: this.balanceData.innerBalance?.value ?? 0
      });

      totalWorth += this.balanceData.innerBalance?.value ?? 0;

      // Add metal-specific rows
      this.metalCommodities.forEach(metal => {
        // Find the corresponding metal balance in the balanceData
        const metalBalance = this.balanceData.metalBalances?.find(
          balance => balance.metalFundType?.id === metal.metalAccountTypeId
        );


        const matchingPrice = (this.realPriceData ?? []).find(price => price.CODE === metal.metalCode);

        let worth = -matchingPrice?.ASK * metalBalance?.innerBalance?.value ?? '';

        if (worth) {
          totalWorth += worth;
        }

        result.push({
          title: metal.name,
          innerBalance: metalBalance?.innerBalance?.value ?? 0,
          price: matchingPrice?.ASK ?? '',
          worth: worth
        });
      });

      result.push({
        title: '',
        innerBalance: '',
        price: '合计',
        worth: totalWorth,
      });

      return result;
    },

    showStoreOption() {
      return (Engine.getOrgSettings().multiStoreMode ||
        Engine.getOrgSettings().forceToShowOrderStoreInfo);
    }
  },
  async mounted() {
    await this.loadMetalCommodities();
    await this.loadData();

    this.metalUtil.subscribe(this.metalPriceUpdated);
  },

  destroyed() {
    this.metalUtil.unsubscribe(this.metalPriceUpdated);
  },

  beforeUnmount() {
    this.metalUtil.unsubscribe(this.metalPriceUpdated);
  },

  deactivated() {
    this.metalUtil.unsubscribe(this.metalPriceUpdated);
  },

  methods: {

    showMetalPurchase() {
      uiNavigation.showMetalPurchaseDetailPage(this.$router, {});
    },

    showMetalSales() {
      uiNavigation.showMetalSalesDetailPage(this.$router, {});
    },

    showTransactions() {
      uiNavigation.showCustomerTransitionExcelPage(this.$router, {});
    },
    async loadMetalCommodities() {
      try {
        const res = await this.commodityUiAction.getCommoditySpecList(
          new DataPage(1, 0, 100),
          (new SubCommodityFilter({
            metalType: SubCommodityMetalFilterTypeEnum.MetalSelfOnly
          })).toJson()
        );

        if (res?.data?.dataList) {
          this.metalCommodities = res.data.dataList;
        }
      } catch (error) {
        console.error('Error loading metal commodities:', error);
      }
    },

    async refreshData() {     
      delCombineOrderInOutStatic();
      delCurrentPeriodBalance();
      deleteFundAccountListNetworkCacheData();
      this.loadData();
    },

    async loadData() {
       this.refreshing = true;
      try {
        await Promise.all([
          this.loadRecoverySalesData(),
          this.loadBalanceData(),
          this.loadFundAccounts() // Refresh fund accounts as well
        ]);
      } finally {
        this.refreshing = false;
      }
    },

    async loadRecoverySalesData() {
      this.loadingRecoveryData = true;
      try {
        // Load metal commodities first if not loaded
        if (this.metalCommodities.length === 0) {
          await this.loadMetalCommodities();
        }

        const result = await this.metalUiAction.getCombineOrderInOutStatic({});
        if (result && Array.isArray(result)) {
          this.recoverySalesData = this.processRecoverySalesData(result);
        } else if (result && result.data) {
          this.recoverySalesData = this.processRecoverySalesData(
            Array.isArray(result.data) ? result.data : [result.data]
          );
        }
      } catch (error) {
        console.error('Error loading recovery sales data:', error);
      } finally {
        this.loadingRecoveryData = false;
      }
    },

    processRecoverySalesData(data) {
      // Add sales and purchase counts for each metal type to each row

      console.log('processRecoverySalesData');

      let salesData = data.map(row => {
        const processedRow = {
          title: row.title,
          receivedAmount: row.receivedAmount,
          paymentAmount: row.paymentAmount,
        };

        // Process each metal commodity
        this.metalCommodities.forEach(metal => {

          const balance = row.metalBalances?.find(
            balance => balance.metalFundType?.id === metal.metalAccountTypeId
          );

          processedRow[`sales_${metal.id}`] = balance?.outCount?.value ?? 0;
          processedRow[`purchase_${metal.id}`] = balance?.inCount?.value ?? 0;
        });

        return processedRow;
      });

      console.log('processRecoverySalesData salesData:', salesData);

      return salesData;
    },

    async loadBalanceData() {
      this.loadingBalanceData = true;
      try {
        const result = await this.metalUiAction.getCurrentPeriodBalance({});
        if (result) {
          this.balanceData = result;
        }
      } catch (error) {
        console.error('Error loading balance data:', error);
      } finally {
        this.loadingBalanceData = false;
      }
    },

    // New method to load fund accounts
    async loadFundAccounts() {
      this.loadingFundAccounts = true;
      try {
        const res = await this.fundUiAction.getFundAccountData({
          pageInfo: new DataPage(1, 0, 1000), // Get all accounts
          filter: this.filter
        })

        if (res && res.data && res.data.dataList) {
          // Sort fund accounts according to [AU, AG, PT, PD] order
          this.fundAccountList = this.sortFundAccounts(res.data.dataList);
        } else if (res.resErr) {
          console.error('获取资金账户失败', res.resErr);
        }
      } catch (error) {
        console.error('获取资金账户失败', error);
      } finally {
        this.loadingFundAccounts = false;
      }
    },

    // Sort fund accounts by priority: AU, AG, PT, PD, others at the end
    sortFundAccounts(accounts) {
      // Define the priority order
      const priorityOrder = ['AU', 'AG', 'PT', 'PD'];

      return [...accounts].sort((a, b) => {
        // Get priority for account a
        const indexA = priorityOrder.findIndex(code =>
          a.name && a.name.toUpperCase().includes(code)
        );

        // Get priority for account b
        const indexB = priorityOrder.findIndex(code =>
          b.name && b.name.toUpperCase().includes(code)
        );

        // If both have priority codes, sort by priority order
        if (indexA !== -1 && indexB !== -1) {
          return indexA - indexB;
        }

        // If only a has a priority code, a comes first
        if (indexA !== -1 && indexB === -1) {
          return -1;
        }

        // If only b has a priority code, b comes first
        if (indexA === -1 && indexB !== -1) {
          return 1;
        }

        // If neither has a priority code, maintain original order (or alphabetical)
        return 0;
      });
    },

    formatProfit(row) {
      const received = row.receivedAmount?.value ?? 0;
      const payment = row.paymentAmount?.value ?? 0;
      const profit = received - payment;

      if (payment === 0) {
        return `${profit} (0%)`;
      }

      const percentage = ((profit / payment) * 100).toFixed(2);
      return `${profit} (${percentage}%)`;
    },

    // 订阅贵金属价格
    metalPriceUpdated(data) {
      console.log('metalPriceUpdated', data);
      this.realPriceData = data[0];
    },

    // Get metal price for a fund account
    getMetalPrice(account) {
      // Check if this is a metal account with selfDefFundAccountType
      if (!account.selfDefFundAccountType || !this.realPriceData) {
        return '';
      }

      // Find the matching metal commodity
      const metal = this.metalCommodities.find(
        m => m.metalAccountTypeId === account.selfDefFundAccountType.id
      );

      if (!metal) {
        return '';
      }

      // Find the real-time price for this metal
      const priceData = this.realPriceData.find(
        p => p.CODE === metal.metalCode
      );

      return priceData ? priceData.ASK : '';
    },

    // Calculate market value for a fund account
    getMarketValue(account) {
      const price = this.getMetalPrice(account);
      if (!price || !account.balance) {
        return '';
      }

      return price * account.balance;
    }
  }
};
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.quick-menu-section {
  margin-bottom: 20px;
  padding: 15px 0;
  background-color: #f5f7fa;
  border-radius: 8px;
  max-width: 1500px;
}

.quick-menu-title {
  font-weight: bold;
  font-size: 16px;
  margin-left: 20px;
  margin-bottom: 10px;
  color: #303133;
}

.quick-menu {
  display: flex;
  justify-content: space-between;
  /* Change to space between */
  align-items: center;
  padding: 0 20px;
}

.menu-items {
  display: flex;
  justify-content: flex-start;
  gap: 30px;
}

.refresh-button {
  margin-left: auto;
  /* Push to the right */
}

.menu-item:hover {
  color: #409eff;
  transform: translateY(-2px);
}

.menu-icon {
  font-size: 24px;
  margin-bottom: 5px;
}

.blue-icon {
  color: #409eff;
  /* Blue color for icons */
}

.menu-label {
  font-size: 14px;
}


.data-card {
  margin-bottom: 20px;
  max-width: 1500px;
}

.card-header {
  font-weight: bold;
  font-size: 16px;
}

.equal-height-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.equal-height-card :deep(.el-card__body) {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.equal-height-card :deep(.el-table) {
  flex: 1;
}
</style>